#!/usr/bin/env python
# -*- coding: utf-8 -*-
from lib.format_time import *
from lib.HandleMysql import *
from lib.handle_mongo import *
from lib.switch_code import *
from zhineng_conn import *
from config_tools import *
from imc_conn import *
from lib.load_data import *
import urllib
import json
import time
import math
import sys
import re
reload(sys)
sys.setdefaultencoding('utf-8')

def get_ad_attr_info(date,s58):
    bid_conn = set_bid_conn()
    dict_conn = set_dict_conn()
    ib_conn = set_ib_conn()
    line_list = []
    stat_table='ad_info_data'
    

    ## get entity_id from creative_info databases
    for i in range(8):
        query = "select distinct entity_id from creative_info_%s where entity_type=0 and date(add_time)='%s'"%(i,date)
        items = bid_conn.get_results(query)
        if len(items) == 0:
            continue
        
        for item in items:
            info_id = item[0]
            #print info_id
            list_name = ''
            
            params = ''
            info = None
            try:
                info = s58.get_info(info_id)
            except Exception:
                continue
            
            
            #print info
            if info == None:
                continue
            info_cate_id = info.getCateID()
            print "info_cate_id=%s \n" %info_cate_id
            url = info.getUrl()
            print "url=%s \n" %url
            url = url.replace("http://","")
            list_names = url.strip("/").split("/")
            list_name =  list_names[1]
            print "list_name=%s \n" %list_name
            state = info.getState()
            params = info.getParams()
            print "params=%s \n" %params
            #print params
            # 
            if params == None or params == '':
                continue
            p_list = None
            try:
                params = params.replace("'",'"')
                #print params
                p_list = eval(params)
            except Exception:
                #print params
                continue
           
            
            full_path = ''

            new_param = get_param_val(p_list,new_param_id)
            #print new_param
            if new_param == None:
                pass
            else:
                pass
                        
            #print new_param,full_path
            if full_path == '':
                full_path = defualt_full_path               
                
            q = "select dispcategoryid,catename from t_dispcategory where dispcategoryid in (%s) order by depth asc"%full_path
            cates = dict_conn.get_results(q)
            
            cat1 = 0
            cat1name = ''
            cat2 = 0
            cat2name=''
            cat3 = 0
            cat3name=''
            cat4 = 0
            cat4name=''
            cat5 = 0
            cat5name=''
            if cates != None:
                if len(cates) > 0:
                    cat1 = cates[0][0]
                    cat1name = cates[0][1]
                if len(cates) > 1:
                    cat2 = cates[1][0]
                    cat2name=cates[1][1]
                if len(cates) > 2:
                    cat3 = cates[2][0]
                    cat3name=cates[2][1]
                if len(cates) > 3:
                    cat4 = cates[3][0]
                    cat4name=cates[3][1]
                if len(cates) > 4:
                    cat5 = cates[4][0]
                    cat5name=cates[4][1]
            url = "%s%sx.shtml"%(url,info_id)
            param = [info_id,cat1,cat1name,cat2,cat2name,cat3,cat3name,cat4,cat4name,cat5,cat5name,che_xing_cal,url,price,se_price,car_age,cheling_val,pai_liang,li_cheng,params,cate_id,state]
            line_list.append('\t'.join(map(lambda i : str(i), param)))
    if len(line_list) > 0:   
        cont = '\n'.join(line_list)
        cont += '\n'
        path = "/work3/opt/analytic/python/ad_attr_info/"
        file_name = "ad_attr_info_%s.txt"%date.replace('-',"")
        writeTextToFile(path,file_name,"w",cont)    
        #print cont
        load_data(ib_conn,path+file_name,stat_table,'\t')      
    
    bid_conn.close()
    dict_conn.close()
    ib_conn.close()



def get_param_val(p_list,p_id):
    for p in p_list:
        if str(p.get("I")) == p_id:
            return p.get("V")
        
    return None
    
def urldecode(query):
    d = {}
    a = query.split('&')
    for s in a:
        if s.find('='):
            k,v = map(urllib.unquote, s.split('='))
            try:
                d[k].append(v)
            except KeyError:
                d[k] = [v]

    return d



def execute(date,s58):
    try:
        get_ad_attr_info(date,s58)
    except Exception,e:
        print 'get_ad_attr_info:',e

def main():

   #date = '2012-05-28'
   #execute(date)   
   if len(sys.argv)==1:
        start_date=get_yesterday()
        end_date=start_date
   elif len(sys.argv)==2:
        start_date = format_date(sys.argv[1])
        end_date = start_date
   elif len(sys.argv)==3:
        start_date = format_date(sys.argv[1])
        end_date = format_date(sys.argv[2])
   stat_date = start_date
   s58 = Service58()
   while stat_date >= start_date and stat_date <= end_date:
        print "The program of the date of %s is beginning at %s " %(stat_date,get_now())
        execute( stat_date,s58)
        print "The program of the date of %s is end at %s " %(stat_date,get_now())
        stat_date = var_date(stat_date)


if __name__=='__main__':
    main()